library(Biostrings)
library(XML)

baseDir <- "/home/haseong/alpha/dev/FT-NGS"
targetDir <- "/home/haseong/alpha/dev/FT-NGS"
dbName <- "/home/haseong/alpha/apps/blast/db/nt"
setwd(baseDir)

##file.names<-dir(pattern="*.fna")
file.names<-dir(pattern="^KHS.*fna$")


for(fn in file.names){
  contig.file<-paste(baseDir, "/", fn, sep="")
  contig.seqs<-readDNAStringSet(contig.file, "fasta")
  
  out.dir<-paste(targetDir, "/out_", fn, sep="")
  for(j in 1:length(contig.seqs)){
    sel.contig.seq<-contig.seqs[j]
    rev.contig.seq<-reverseComplement(sel.contig.seq)    
    writeXStringSet(sel.contig.seq, "./pattern.fasta", format="fasta")
    contig.name<-unlist(strsplit(names(sel.contig.seq), split=" "))[1]
    if(j==1){
      ## if dir doesn't exist
      if(sum(list.dirs(targetDir)==out.dir)==0){
        system(paste("mkdir ", out.dir, sep=""))
      }
    }
    run.string<-paste("blastn -query pattern.fasta -outfmt 5 -out ",  out.dir, "/", contig.name, ".xml -db ", dbName, sep="")
    system(run.string)
    ##if(j%%10==0){       cat(".");flush.console();  }
    cat(".");flush.console();
    if(j%%50==0){      cat(j, "/", length(contig.seqs), "\n");flush.console();  }
  }
  cat(fn, "\n")
}



